﻿
// szCommDlg.cpp: 实现文件
//

#include "pch.h"
#include "framework.h"
#include "szComm.h"
#include "szCommDlg.h"
#include "afxdialogex.h"


#include "SerialPort.h"
#include "TimerCounter.hpp"

#include "Btsdk_Macro.h"
#include "Btsdk_Stru.h"
#include "Btsdk_API.h"
#include "Btsdk_ui.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// 对话框数据
#ifdef AFX_DESIGN_TIME
	enum { IDD = IDD_ABOUTBOX };
#endif

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CszCommDlg 对话框



CszCommDlg::CszCommDlg(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_SZCOMM_DIALOG, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CszCommDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_LIST1, m_listbox);
}

BEGIN_MESSAGE_MAP(CszCommDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON1, &CszCommDlg::OnBnClickedButton1)
	ON_BN_CLICKED(IDC_BUTTON2, &CszCommDlg::OnBnClickedButton2)
	ON_BN_CLICKED(IDC_BUTTON3, &CszCommDlg::OnBnClickedButton3)
	ON_WM_TIMER()
	ON_BN_CLICKED(IDC_BUTTON4, &CszCommDlg::OnBnClickedButton4)
	ON_BN_CLICKED(IDC_BUTTON5, &CszCommDlg::OnBnClickedButton5)
	ON_BN_CLICKED(IDC_BUTTON6, &CszCommDlg::OnBnClickedButton6)
	ON_BN_CLICKED(IDC_BUTTON7, &CszCommDlg::OnBnClickedButton7)
	ON_BN_CLICKED(IDC_BUTTON8, &CszCommDlg::OnBnClickedButton8)
	ON_BN_CLICKED(IDC_BUTTON9, &CszCommDlg::OnBnClickedButton9)
	ON_BN_CLICKED(IDC_BUTTON10, &CszCommDlg::OnBnClickedButton10)
	ON_BN_CLICKED(IDC_BUTTON11, &CszCommDlg::OnBnClickedButton11)
END_MESSAGE_MAP()


// CszCommDlg 消息处理程序

BOOL CszCommDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != nullptr)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	// TODO: 在此添加额外的初始化代码
	freopen("D:\\output.txt", "w+", stdout);
	SetDlgItemInt(IDC_EDITTIMER,100);
	SetDlgItemText(IDC_MFCMASKEDEDIT1, "80:FB:F0:9D:A3:27");
	Btsdk_Init();
	m_listbox.AddString("bt Mac:");
	m_listbox.AddString("1");
	m_listbox.AddString("1");
	m_listbox.AddString("1");
	m_listbox.AddString("1");
	m_listbox.AddString("1");
	m_listbox.AddString("1");
	m_listbox.AddString("1"); 
	m_listbox.AddString("1");
	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

void CszCommDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CszCommDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CszCommDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}



CSerialPort sp;
TimerCounter tc;
UINT8 buffer[20 * 1024];
#pragma comment(lib,"BsSDK.lib")
#define REMOTE_MAC_0 0x00000000
UINT8 templete[4][3620];
UINT8 deviceID[4] = { 0 };
UINT8 authCode[4] = { 0x12,0x56,0x98,0xab };
UINT8 authKey = 0;
int sendState = 0;
BTUINT32 OSComport = 6;
/*
*	cmd: 0 head, 1 data, 2 tail,3 time
*	fseq: 0..3
*	pseq: 0..3
*/
void prepareData(UINT8* buffer, int* len, UINT8 cmd, UINT8 fseq, UINT16 pseq) {
	static UINT16 seq = 0;
	UINT16 u16len = 0;
	UINT16 checksum = 0;
	buffer[0] = 0xaa;
	buffer[1] = 0x55;

	buffer[3] = seq&0xff;
	buffer[4] = (seq>>8) & 0xff;

	buffer[7] = deviceID[0];
	buffer[8] = deviceID[1];
	buffer[9] = deviceID[2];
	buffer[10] = deviceID[3];

	buffer[11] = authCode[0];
	buffer[12] = authCode[1];
	buffer[13] = authCode[2];
	buffer[14] = authCode[3];

	switch (cmd) {
	case 0:
		u16len = 22;
		buffer[2] = 0;
		buffer[15] = 4;	//total finger num
		buffer[16] = 4;
		buffer[17] = 0;
		buffer[18] = 4;
		buffer[19] = 0;
		buffer[20] = 4;
		buffer[21] = 0;
		buffer[22] = 4;
		buffer[23] = 0;
		break;
	case 1:
		u16len = 905 + 16;
		buffer[2] = 1;
		buffer[15] = fseq+1;
		buffer[16] = pseq & 0xff;
		buffer[17] = (pseq >> 8) & 0xff;
		for (int i = 0; i < 905; i++) {
			buffer[18 + i] = templete[fseq][905 * pseq];
		}
		break;
	case 2:
		u16len = 13;
		buffer[2] = 2;
		break;
	case 3:
		break;
	default:
		break;
	}
	buffer[5] = u16len & 0xff;
	buffer[6] = (u16len >> 8) & 0xff;
	for (int i = 2; i < u16len+2; i++) {
		buffer[i] ^= authKey;
		checksum += buffer[i];
	}
	buffer[u16len + 2] = checksum & 0xff;
	buffer[u16len + 3] = (checksum >> 8) & 0xff;
	//
	seq++;
	*len = u16len + 4;
}
void CszCommDlg::OnBnClickedButton1()
{
	// TODO: 在此添加控件通知处理程序代码
	//Serial port part
	tc.Start();
	int port = OSComport;	//1 to 4
	int r = sp.InitPort(this->m_hWnd, port, 115200);
	if (!r) {
		CString cs;
		cs.Format("serial port init Fail!");
		SetDlgItemText(IDC_STATUS, cs);
		return;
	}
	r = sp.StartMonitoring();
	if (!r) {
		sp.StopMonitoring();
		CString cs;
		cs.Format("serial port open Fail!");
		SetDlgItemText(IDC_STATUS, cs);
		return;
	}
	CString cs;
	cs.Format("serial port open success!");
	SetDlgItemText(IDC_STATUS, cs);
	tc.Stop();
}

void CszCommDlg::OnBnClickedButton2()
{
	// TODO: 在此添加控件通知处理程序代码
	//bt part
	tc.Start();
	//spp connect 
	BtSdkSPPConnParamStru sppStru = { 0 };
	sppStru.size = sizeof(BtSdkSPPConnParamStru);
	sppStru.com_index = OSComport;	//connect to this com port
	BTDEVHDL btdh;
	BTUINT8 bd_addr[] = { 0x27,0xA3,0x9D,0xf0,0xfb,0x80 };//"80FBF09DA327";
	BTCONNHDL btcnth;
	btdh = Btsdk_GetRemoteDeviceHandle(bd_addr);
	BTINT32 btret = Btsdk_ConnectEx(btdh	//if the before connection not disconnect, will cause error
		,  BTSDK_CLS_SERIAL_PORT	//spp class
		, (BTINT32)&sppStru
		, &btcnth
	);
	if (btret == BTSDK_OK)	{
		printf("Connect remote SPP Service with local COM%d\n", OSComport);
	}
	tc.Stop();
}

#include "btsocket.h"
void CszCommDlg::OnBnClickedButton3()
{
	//!!!!!!!!!!! this part don't test before all!!!!!!!!!!!!!!
	// TODO: 在此添加控件通知处理程序代码
	SOCKADDR_BTH bthSockAddr;
	bthSockAddr.btAddr = 0x80FBF09DA327;
	//NameToBthAddr("", &bthSockAddr);

	int ret = BthSocketInit();
	ret = BthSocketConnectTo(bthSockAddr);
}


void CszCommDlg::OnTimer(UINT_PTR nIDEvent)
{
	// TODO: 在此添加消息处理程序代码和/或调用默认值
	int u16len = 0;
	UINT8 fseq = 0;
	UINT16 pseq = 0;
	UINT8 cmd = 0;
	if (sendState == 0) {	//head
		cmd = 0;
	}else if (sendState >= 1 && sendState <= 16) {	//data
		cmd = 1;
		fseq = (sendState - 1) / 4;
		pseq = (sendState - 1) % 4;
	}else if (sendState == 17) {	//tail
		cmd = 2;
	}else {
		sendState = 0;
		KillTimer(nIDEvent);
		return;
	}
	prepareData(reinterpret_cast<UINT8*>(buffer), &u16len, cmd,fseq,pseq);

	sendState++;
	if (nIDEvent == 1) {	//serial port timer
#if 0
		char filename[256];
		sprintf(filename, "D://%d_%d_%d.txt", cmd,fseq, pseq);
		FILE* fp;
		fp = fopen(filename, "w+");
		for (int i = 0; i < u16len; i++) {
			fprintf(fp, "0x%x ", (unsigned char)buffer[i]);
			if (i % 10 == 0) fprintf(fp,"\r\n");
		}
		fclose(fp);
#endif
		sp.WriteToPort(reinterpret_cast<BYTE*>(buffer), u16len);
	}
	else if (nIDEvent == 2) {	//socket send timer
		BthSocketSend(reinterpret_cast<LPSTR>(buffer), u16len);
	}
	CString cs;
	cs.Format("send data: length: %d,state:%d,data: 0x%x,0x%x,..."
		, u16len, sendState, buffer[0], buffer[1]);
	SetDlgItemText(IDC_STATUS, cs);
	CDialogEx::OnTimer(nIDEvent);
}


void CszCommDlg::OnBnClickedButton4()
{
	// TODO: 在此添加控件通知处理程序代码
	int gap = GetDlgItemInt(IDC_EDITTIMER);
	SetTimer(1, gap, NULL);

}


void CszCommDlg::OnBnClickedButton5()
{
	// TODO: 在此添加控件通知处理程序代码
	KillTimer(1);
}


void CszCommDlg::OnBnClickedButton6()
{
	// TODO: 在此添加控件通知处理程序代码
	BthSocketClose();
}


void CszCommDlg::OnBnClickedButton7()
{
	// TODO: 在此添加控件通知处理程序代码
	FILE* fp;
	if ((fp = fopen("templete1.bin", "rb")) != nullptr) {
		fread(templete[0], 1, 3620, fp);
		fclose(fp);
	}
	else printf("error open file templete1.bin\r\n");
	
	if ((fp = fopen("templete2.bin", "rb")) != nullptr) {
		fread(templete[1], 1, 3620, fp);
		fclose(fp);
	}
	else printf("error open file templete2.bin\r\n");

	if ((fp = fopen("templete3.bin", "rb")) != nullptr) {
		fread(templete[2], 1, 3620, fp);
		fclose(fp);
	}
	else printf("error open file templete3.bin\r\n");

	if ((fp = fopen("templete4.bin", "rb")) != nullptr) {
		fread(templete[3], 1, 3620, fp);
		fclose(fp);
	}
	else printf("error open file templete4.bin\r\n");
}


void CszCommDlg::OnBnClickedButton8()
{
	// TODO: 在此添加控件通知处理程序代码
	//initialize com port obj
	tc.Start();
	BTUINT32 s_comSerialNum = Btsdk_GetASerialNum();//gets a currently available serial number of COM port.
	Btsdk_PlugInVComm(s_comSerialNum	//com port if not exists, install com driver
		, &OSComport	//[in/out] Pointer to buffer containing Com port number specified by OS
		, 1				//fixed value
		, COMM_SET_RECORD | COMM_SET_USAGETYPE
		, 2200);	//time out
	BTINT32 ulRet = Btsdk_InitCommObj((BTUINT8)OSComport, BTSDK_CLS_SERIAL_PORT);//set Bluetooth com port
	if (ulRet != BTSDK_OK)
	{
		printf("btsdk init comm error: %d", ulRet);
	}
	tc.Stop();
}


void CszCommDlg::OnBnClickedButton9()
{
	// TODO: 在此添加控件通知处理程序代码
	sp.StopMonitoring();
	sp.ClosePort();

}

#define MAX_DEV_NUM 100
void CszCommDlg::OnBnClickedButton10()
{
	// TODO: 在此添加控件通知处理程序代码
	BTUINT8 szBdAddr[10];
	BTSDKHANDLE hEnumHdl = BTSDK_INVALID_HANDLE;
	BTDEVHDL s_rmt_dev_hdls[MAX_DEV_NUM] = { 0 };
	INT i = 0;
	BTINT32 s_rmt_dev_num = 0;
	memset(s_rmt_dev_hdls, 0, sizeof(s_rmt_dev_hdls));

	hEnumHdl = Btsdk_StartEnumRemoteDevice(BTSDK_ERD_FLAG_NOLIMIT, 0);
	if (BTSDK_INVALID_HANDLE != hEnumHdl)
	{
		for (i = 0; i < MAX_DEV_NUM; i++)
		{
			s_rmt_dev_hdls[i] = Btsdk_EnumRemoteDevice(hEnumHdl, NULL);
			if (BTSDK_INVALID_HANDLE == s_rmt_dev_hdls[i])
			{
				s_rmt_dev_hdls[i] = BTSDK_INVALID_HANDLE;
				break;
			}
			Btsdk_GetRemoteDeviceAddress(s_rmt_dev_hdls[i], szBdAddr);
			CString cs;
			cs.Format("%x:%x:%x:%x:%x:%x"
				, szBdAddr[5]
				, szBdAddr[4]
				, szBdAddr[3]
				, szBdAddr[2]
				, szBdAddr[1]
				, szBdAddr[0]);
			m_listbox.AddString(cs);
			s_rmt_dev_num++;
		}
		Btsdk_EndEnumRemoteDevice(hEnumHdl);
		hEnumHdl = BTSDK_INVALID_HANDLE;
	}
}

#define HCHAR2INT(x) ((x>='0'&&x<='9')? (x-'0'):((x>='a'&&x<='f')?(x-'a'+10):(x-'A'+10)))
void CszCommDlg::OnBnClickedButton11()
{
	// TODO: 在此添加控件通知处理程序代码
	BTUINT8 szBdAddr[10];
	BTDEVHDL tdevhdl = 0;
	CString cs;
	GetDlgItemText(IDC_MFCMASKEDEDIT1, cs);
	szBdAddr[5] = (HCHAR2INT(cs[0]) << 4) | HCHAR2INT(cs[1]);
	szBdAddr[4] = (HCHAR2INT(cs[2]) << 4) | HCHAR2INT(cs[3]);
	szBdAddr[3] = (HCHAR2INT(cs[4]) << 4) | HCHAR2INT(cs[5]);
	szBdAddr[2] = (HCHAR2INT(cs[6]) << 4) | HCHAR2INT(cs[7]);
	szBdAddr[1] = (HCHAR2INT(cs[8]) << 4) | HCHAR2INT(cs[9]);
	szBdAddr[0] = (HCHAR2INT(cs[10]) << 4) | HCHAR2INT(cs[11]);

	tdevhdl = Btsdk_AddRemoteDevice(szBdAddr);
	if (BTSDK_INVALID_HANDLE == tdevhdl) {
		SetDlgItemText(IDC_STATUS, "add error mac");
	}
}
